package cn.itcast.servlet;

import cn.itcast.domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //解决乱码问题
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");

            //接收表单数据
            Map<String, String[]> map = request.getParameterMap();
            User user = new User();

            //将数据封装到user类中
            BeanUtils.populate(user,map);

            //新建字符缓冲输出流,用以储存数据
            BufferedWriter bw = new BufferedWriter(new FileWriter("D:/user.txt", true));
            bw.write(user.getUsername()+","+user.getAge()+","+user.getScore());
            bw.newLine();

            //重定向到SuccessServlet
            response.sendRedirect(super.getServletContext()+"/successServlet");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
